"""处理专业管理的views"""
# =========== 导入模块 ===========
from django.shortcuts import render
# 导入models中的类
from basicweb.models import Major
# 导入JSONResponse
from django.http import JsonResponse
# 导入Q查询
from django.db.models import Q


# ============ views函数 ===========
def index(request):
    return render(request, 'basic/major.html')


def list_views(request):
    """获取数据库中的专业信息"""
    # 获取传递过来的数据
    page = int(request.POST.get('page'))
    limit = int(request.POST.get('limit'))
    q_str = request.POST.get('inputStr')
    # 获取所有的对象
    objs = list(Major.objects.filter(Q(name__icontains=q_str) | Q(faculty__name__icontains=q_str)).
                values('id', 'name', 'faculty_id', 'faculty__name'))
    # 获取当前页的数据
    current_page_data = objs[(page - 1) * limit: page * limit]
    # 定义返回数据的数据结构
    res = {'code': 0, 'count': len(objs), 'data': current_page_data}
    # 返回数据
    return JsonResponse(res)


def add_value(request):
    """实现专业信息的添加"""
    # 获取传递过来的数据
    rec = request.POST
    # 定义返回值类型
    res = {'status': True}
    # 使用异常处理添加
    try:
        Major.objects.create(name=rec.get('major'), faculty_id=rec.get('faculty'))
    except Exception as e:
        res['status'] = False
        res['error'] = "数据添加提交到数据库失败，具体原因：" + str(e)

    # 返回
    return JsonResponse(res)


def edit_value(request):
    """实现专业信息的添加"""
    # 获取传递过来的数据
    rec = request.POST
    # 定义返回值类型
    res = {'status': True}
    # 使用异常处理添加
    try:
        # 获取到当前的记录
        obj = Major.objects.get(id=rec.get('major_id'))
        # 修改
        obj.name = rec.get('major')
        obj.faculty_id = rec.get('faculty')
        # 保存
        obj.save()
    except Exception as e:
        res['status'] = False
        res['error'] = "数据修改提交到数据库失败，具体原因：" + str(e)

    # 返回
    return JsonResponse(res)


def del_value(request):
    """删除对象"""
    # 获取传递过来的数据
    rec = request.POST
    # 定义返回值类型
    res = {'status': True}
    # 使用异常处理添加
    try:
        # 删除
        Major.objects.get(id=rec.get('major_id')).delete()

    except Exception as e:
        res['status'] = False
        res['error'] = "数据删除提交到数据库失败，具体原因：" + str(e)

    # 返回
    return JsonResponse(res)


def get_major_by_faculty(request):
    """根据院系返回该院系下面的专业"""
    # 接收传递过来的院系的ID
    faculty_id = request.POST.get('faculty_id')
    # 获取
    objs = list(Major.objects.filter(faculty_id = faculty_id).values('id','name'))
    # 返回
    return JsonResponse({'data': objs})
